<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Admin\Controller;

/**
 * 渠道信息
 */
class ChannelController extends HomeController {

    public function _initialize(){
        parent::_initialize();
        $this->is_login();      //判断是否登录
    }

    //渠道列表
	public function get_list(){
        $requestdata = file_get_contents("php://input");
        $paramData = json_decode($requestdata, true);
        $model = D("Channel");
        $field = "a.*,a.id as channel_id,DATE_FORMAT(FROM_UNIXTIME(a.create_time), '%Y-%m-%d %H:%i') as create_date,b.channel_name as pid_channel_name";
        $result = $model->get_channel_list($paramData,$field);
        $pid_result = $model->get_channel_list(['pid'=>0],"a.id as pid,a.channel_name",false);
        foreach($result['list'] as $key=>$val){
            if($val['pid'] == 0){
                $val['pid'] = NULL;
            }
            $result['list'][$key] = $val;
        }

        $returnData = [
            'code'      => 200,
            'data'      => $result['list']?$result['list']:[],
            'total'     => $result['count'],
            'pid_list'  => $pid_result['list'] ,
        ];
        echo json_encode($returnData);
    }


    //添加/修改渠道
    public function save(){
        $requestdata = file_get_contents("php://input");
        $paramData = json_decode($requestdata, true);
        $model = D("Channel");
        if(empty($paramData['channel_name'])) $this->throw_exception('渠道名称不能为空');
        $paramData['userId'] =  $this->user_info['id'];
        $result = $model->channel_save($paramData);
        $this->throw_exception($result['msg'],$result['code']);
    }



    //渠道二维码
    public function get_applet_qrcode(){
        $requestdata = file_get_contents("php://input");
        $paramData = json_decode($requestdata, true);
        if(empty($paramData['channel_id'])) $this->throw_exception('渠道编码不能为空');
        $token = $this->getAppletToken($this->APPLET_APPID, $this->APPLET_SECRET);
        if (empty($token)) $this->throw_exception('获取小程序token失败');
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$token}";
        $data = [
            'page' => "pages/home/index",
            'scene' => $paramData['channel_id'],
        ];
        $qrcode = $this->httpRequest($url, json_encode($data), 'POST');
        if (empty($qrcode)) $this->throw_exception('网络异常,请稍后在试');

        $isExist = file_exists('./Public/static/applet_qrcode');
        //没有文件夹的时候
        if (empty($isExist))  mkdir('./Public/static/applet_qrcode/', 0777, true);
        $img = "./Public/static/applet_qrcode/{$paramData['channel_id']}_qrcode.png";
        file_put_contents($img, $qrcode); // 保存为文件
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $image = $protocol . $_SERVER['HTTP_HOST'] . trim($img,'.');
        $returnData = ['code' => 200, 'data' => ['image' => $image]];
        echo json_encode($returnData);
    }




    //渠道推荐列表
    public function get_channel_recommend_list(){
        $requestdata = file_get_contents("php://input");
        $paramData = json_decode($requestdata, true);
        $ChannelRecommendModel = D("ChannelRecommend");
        if(empty($paramData['date'])) $this->throw_exception('日期不能为空');
        $result = $ChannelRecommendModel->get_channel_recommend_list($paramData);
        $list = $result['list'];
        if($list){
            $info = [
                'channel_id'       => NULL,
                'channel_name'     => '',
                'pid_channel_name' => '合计',
            ];
            $header = [
                'pid_channel_name'  => '一级渠道',
                'channel_name'      => '子渠道',
            ];
            foreach($result['date_list'] as $val){
                $info[$val]   = array_sum(array_column($list,$val));
                $header[$val] = $val;
            }
            $list[] = $info;
        }
        if($paramData['excel']){
            $this->execl_down($header,$list);
        }else{
            $returnData = [
                'code' => 200,
                'data' => $list ? $list : [],
            ];
            echo json_encode($returnData);
        }

    }
}